package org.example.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class WebUtil {

    private static final ObjectMapper M = new ObjectMapper();

    static {
        //设置序列化的日期格式
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        M.setDateFormat(df);
    }

    //json序列化
    public static void serialize(HttpServletResponse resp, Object o){
        try {
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            String json = M.writeValueAsString(o);
            resp.getWriter().write(json);
        } catch (IOException e) {
            //这里是序列化就返回响应，捕获到异常，就自行处理
            e.printStackTrace();
            //throw new RuntimeException("json序列化出错", e);
            resp.setStatus(500);
        }
    }

    //反序列化:把请求的json格式数据，转换为Java对象
    public static <T> T deserialize(HttpServletRequest req, Class<T> clazz){
        try {
            return M.readValue(req.getInputStream(), clazz);
        } catch (IOException e) {
            throw new RuntimeException("反序列化失败", e);
        }
    }

}
